package com.letoken.platform.job.jobhandler.monitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.letoken.platform.pub.util.EmailUtil;
import com.letoken.platform.repo.app.dao.AppUserLoginLogMapper;
import com.letoken.platform.repo.app.manager.AppUserLockedManager;
import com.letoken.platform.repo.app.po.AppUserLoginLog;
import com.letoken.platform.repo.app.redis.AppWalletBlackListRedis;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author letokenlabs
 * @date 2023/3/2$
 * 黑名单提醒
 */
@Component
public class UserWalletBlackListNotify {

    @Autowired
    private AppUserLoginLogMapper appUserLoginLogMapper;

    @Autowired
    private AppUserLockedManager appUserLockedManager;

    @XxlJob("UserWalletBlackListNotify")
    public void userWalletBlackListNotify() {

        // xxl后台配置的参数
        // {"netType":"bsc","tokenId":"1","limitAmount":"1000","email":"xxx@gmail.com;xx1@gmail.com"}
        JSONObject params = JSON.parseObject(XxlJobHelper.getJobParam());
        String netType = params.getString("netType");
        String emailTo = params.getString("email");

        List<String> list = new ArrayList<>();

        String item = AppWalletBlackListRedis.me().getPopItem();
        while (!StringUtils.isEmpty(item)) {
            if (!list.contains(item)) {
                list.add(item);
            }
            item = AppWalletBlackListRedis.me().getPopItem();
        }

        boolean alert = list != null && !list.isEmpty();

        if (alert) {

            String subject = String.format("有新的黑名单用户！%s (%s)", netType, list.size());
            StringBuilder sb = new StringBuilder();
            sb.append("<div>有新的黑名单用户 </div><ul>");

            list.forEach(it -> {
                sb.append(String.format("<li style='margin-bottom:5px'>%s</li>", it));
            });

            sb.append("</ul>");

            // 根据deviceId 查询关联的用户，也进行冻结
            QueryWrapper<AppUserLoginLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("DISTINCT app_user_id");
            queryWrapper.apply("device_id in (select DISTINCT device_id from app_user_login_log where app_user_id in ('" + String.join("','", list) + "')) and app_user_id not in (select user_id from app_user_locked where locked=1)");
            List<AppUserLoginLog> relateList = appUserLoginLogMapper.selectList(queryWrapper);

            if (relateList != null && !relateList.isEmpty()) {
                sb.append("<div>以下关联的设备账户也一并拉黑了 </div><ul>");

                relateList.forEach(it -> {

                    // 加入黑名单
                    AppWalletBlackListRedis.me().setValue(it.getAppUserId().toString(), true);

                    // 冻结用户
                    appUserLockedManager.setUserLocked(it.getAppUserId(), true);

                    sb.append(String.format("<li style='margin-bottom:5px'>%s</li>", it.getAppUserId()));
                });
                sb.append("</ul>");
            }

            EmailUtil.sendEmail(emailTo, subject, sb.toString());
        }
    }
}
